package com.grape.bosfore.action;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import com.grape.bosfore.action.common.BaseAction;
import com.grape.bosfore.utils.MailUtils;
import com.grape.crm.domain.Customer;

@Namespace("/customer")
@ParentPackage("json-default")
@Scope("prototype")
@Controller
public class CustomerAction extends BaseAction<Customer>{
	private static final long serialVersionUID = 1L;

	@Action(value="sendSms")
	public void sendSms() throws UnsupportedEncodingException {
		
		// 随机验证码
		r4 = RandomStringUtils.randomNumeric(4);
		System.out.println("生成的验证码为: "+r4);
		
		// session传递
		ServletActionContext.getRequest().getSession().setAttribute(r4, "randomCode");
		
		// 短信模板
		final String str = "尊敬的用户您好，本次获取的验证码为："+r4 + ",服务电话：110";

		// 交给ActiveMQ
		jt.send("bos_sms",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", model.getTelephone());
				mapMessage.setString("msg", str);
				return mapMessage;
			}
		});
		
		
	}
	
	
	@Action(value="regist",results= {
			// 不加/ 报404,把namespace加上了
			@Result(name="error",type="redirect",location="/signup.html"),
			@Result(name="success",type="redirect",location="/signup-success.html")})
	public String regist() {
		if (checkcode.equals("") || !checkcode.equals(r4)) {
			ServletActionContext.getContext().getValueStack().set("error", "验证码错误请重新输入");
			return "error";
		}
		
		// 将用户保存到数据库
		WebClient.create("http://localhost:10001/crm_management/services/customerService/saveOne").
			type(MediaType.APPLICATION_XML).put(model);
		
		
		// 邮件激活码
		String activecode = RandomStringUtils.randomNumeric(32);
		// 保存激活码到redis
		rt.opsForValue().set(model.getTelephone(), activecode,24,TimeUnit.HOURS);
		// 发邮件
		String content = "尊敬的用户您好,请于24小时内点击下方链接,绑定您的账号享受更多便捷<br/>"
				+ "<a href='"+MailUtils.activeUrl+"?telephone="+model.getTelephone()
				+ "&activecode="+activecode+"'>点我绑定~~</a>";
		
		MailUtils.sendMail("速运快递激活邮件", content, model.getEmail());
		
		return SUCCESS;
	}
	
	
	// 账户绑定(激活)邮箱
	// http://localhost:9003/bos_fore/customer/activeMail?telephone=123&activecode=123
	@Action(value="activeMail")
	public void activeMail() throws IOException {
		// 解决乱码
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
		
		// 校验激活码是否正确
		String ac = rt.opsForValue().get(model.getTelephone());
		if (StringUtils.isNotEmpty(ac) && StringUtils.isNotEmpty(activecode) && ac.equals(activecode)) {
			// 调用webService激活
			Customer result = WebClient.create("http://localhost:10001/crm_management/services/customerService/activeMail/"
					+ model.getTelephone())
					.accept(MediaType.APPLICATION_XML)
					.get(Customer.class);
			
			if (result.getType()==null) {
				ServletActionContext.getResponse().getWriter().println("邮箱以绑定,无需重复绑定");
			} else {
				ServletActionContext.getResponse().getWriter().println("邮箱绑定成功");
			}
			
		}else {
			ServletActionContext.getResponse().getWriter().println("无效的激活码");
		}
		
	}
	
	@Action(value="login",results = {@Result(name="success",type="redirect" ,location="/index.html#/myhome"),
			@Result(name="login" ,type="redirect",location="/login.html")})
	public String login() {
		// 远程服务是可以只返回字符串的
		String customerId = WebClient.create("http://localhost:10001/crm_management/services/customerService/login")
			.replaceQueryParam("telephone",model.getTelephone())
			.replaceQueryParam("password", model.getPassword())
			.accept(MediaType.APPLICATION_XML).get(String.class);
		
		if (customerId == null) {
			return "login";
		}
		
		// 存在session可是没办法实现记住登陆的
		ServletActionContext.getRequest().getSession().setAttribute("customerId", customerId);
		return SUCCESS;
	}
	
	
	
	
	
	// ActiveMQ
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jt;
	
	
	// 邮箱激活码
	private String activecode;
	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}


	// 生成的验证码
	private static String r4="";
	
	// 用户提交的验证码
	private String checkcode;
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	// 初始化redis工具
	private RedisTemplate<String,String> rt;
	@Autowired
	public void setRt(RedisTemplate<String, String> rt) {
		this.rt = rt;
		// 没这三行存入乱码:无语
	    RedisSerializer stringSerializer = new StringRedisSerializer();
	    rt.setKeySerializer(stringSerializer);
	    rt.setValueSerializer(stringSerializer);
	}
}
